package com.rc.saas.tenant.controller.enterprise;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.enterprise.*;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberApplySearch;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.enterprise.EnterpriseSubmemberApplyService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.enterprise.EnterpriseSubMemberApplyResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author frog
 * @date 2021/2/7
 */
@Controller
@RequestMapping("/enterpriseSubmemberApply")
public class EnterpriseSubmemberApplyController {

    private static Logger logger = LogManager.getLogger(EnterpriseMemberApplyController.class);

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private MqProducer mqProducer;

    /**
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole tenantRole = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        model.addAttribute("role",tenantRole);
        return "templates/enterprise/enterpriseSubmemberApply/enterpriseSubmemberApply";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andStatusEqualTo("0");
        List<EnterpriseMember> enterpriseList =  enterpriseMemberService.selectByExample(example);
        model.addAttribute("enterpriseList", enterpriseList);
        return "/templates/enterprise/enterpriseSubmemberApply/addEnterpriseSubmemberApply";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(Model model, @PathVariable("id") Long id) {
        TenantUser user = ShiroUtils.getSessionUser();
        EnterpriseSubmemberApply submemberApply = enterpriseSubmemberApplyService.selectByPrimaryKey(id);
        model.addAttribute("submemberApply", submemberApply);
        if (submemberApply.getSubMemberId() != null) {
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(submemberApply.getSubMemberId());
            model.addAttribute("member", memberInfo);

        }
        EnterpriseMemberExample example = new EnterpriseMemberExample();
        example.createCriteria().andStatusEqualTo("0");
        List<EnterpriseMember> enterpriseList =  enterpriseMemberService.selectByExample(example);
        model.addAttribute("enterpriseList", enterpriseList);

        return "/templates/enterprise/enterpriseSubmemberApply/editEnterpriseSubmemberApply";
    }

    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String detail(Model model, @PathVariable("id") Long id) {
        TenantUser user = ShiroUtils.getSessionUser();
        EnterpriseSubmemberApply submemberApply = enterpriseSubmemberApplyService.selectByPrimaryKey(id);
        model.addAttribute("submemberApply", submemberApply);
        if (submemberApply.getSubMemberId() != null) {
            MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(submemberApply.getSubMemberId());
            model.addAttribute("member", memberInfo);

        }
        EnterpriseMember enterprise = enterpriseMemberService.selectByPrimaryKey(submemberApply.getEnterpriseId());
        model.addAttribute("enterprise", enterprise);
        return "/templates/enterprise/enterpriseSubmemberApply/detailEnterpriseSubmemberApply";
    }

    /**
     * 返回企业子会员审核列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageSubmemberApply", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageSubmemberApply(EnterpriseSubMemberApplySearch search) {
        //数据权限
        dataAuth(search);

        PageInfo<EnterpriseSubMemberApplyResult> pageInfo = enterpriseSubmemberApplyService.listPageEntSubmember(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }
    /**
     * 导出企业成员列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(EnterpriseSubMemberApplySearch search, HttpServletResponse response) {
        try {
            //数据权限
            dataAuth(search);

            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(search);
            PageInfo<EnterpriseSubMemberApplyResult> pageInfo = enterpriseSubmemberApplyService.listPageEntSubmember(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("企业成员列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), EnterpriseSubMemberApplyResult.class).sheet("企业成员列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出企业成员列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 数据权限过滤
     * @param search
     * @return
     */
    protected EnterpriseSubMemberApplySearch dataAuth(EnterpriseSubMemberApplySearch search){

        TenantUser user = ShiroUtils.getSessionUser();
        TenantRole tenantRole = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        if ("3".equals(tenantRole.getRoleType())){
            //企业用户
            search.setEnterpriseId(user.getEnterpriseId());
        }else if ("1".equals(tenantRole.getRoleType())){
            //自定义角色
            if (tenantRole.getDataAuth().endsWith("0")){
                //如果不查询企业会员置0
                search.setEnterpriseId(0L);
            }
        }
        return search;
    }


    /**
     * 跳转企业子会员审核记录页面
     *
     * @return
     */
    @RequestMapping(value = "/applyRecord/{submemberApplyId}", method = RequestMethod.GET)
    public String applyRecord(@PathVariable("submemberApplyId") Long submemberApplyId, Model model) {
        EnterpriseSubmemberApply enterpriseSubmemberApply = enterpriseSubmemberApplyService.selectByPrimaryKey(submemberApplyId);
        model.addAttribute("enterpriseSubmemberApply", enterpriseSubmemberApply);
        return "/templates/enterprise/enterpriseSubmemberApply/applyRecord";
    }


    /**
     * 保存企业子会员
     */
    @RequestMapping(value = "/updateSubmemberApply", method = RequestMethod.POST)
    @ResponseBody()
    public TResponse updateSubmemberApply(EnterpriseSubmemberApply enterpriseSubmemberApply) {
        enterpriseSubmemberApplyService.updateSubmemberApply(enterpriseSubmemberApply);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateSubmemberApplyForAudit", method = RequestMethod.POST)
    public TResponse updateSubmemberApplyForAudit(Long id, String status, String reason) {
        enterpriseSubmemberApplyService.updateSubmemberApplyForAudit(id, status, reason);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/deleteSubmemberApply", method = RequestMethod.POST)
    public TResponse deleteSubmemberApply(Long id) {
        enterpriseSubmemberApplyService.deleteSubmemberApply(id);
        return TResponse.SUCCESS();
    }

    /**
     * 新增企业会员
     */
    @ResponseBody()
    @RequestMapping(value = "/addSubmemberApply", method = RequestMethod.POST)
    public TResponse addSubmemberApply(EnterpriseSubmemberApply enterpriseSubmemberApply) {

        if (enterpriseSubmemberApply.getEnterpriseId() != null) {
            if (enterpriseSubmemberApply.getEnterpriseName() == null) {
                EnterpriseMember enterprise = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmemberApply.getEnterpriseId());
                enterpriseSubmemberApply.setEnterpriseName(enterprise.getEnterpriseName());
                enterpriseSubmemberApply.setEnterpriseOwner(enterprise.getEnterpriseOwner());
                enterpriseSubmemberApply.setOwnerMobile(enterprise.getOwnerMobile());
                enterpriseSubmemberApply.setContactName(enterprise.getContactName());
            }

        }

        enterpriseSubmemberApplyService.insertReturnId(enterpriseSubmemberApply);

        Map<String, Long> map = new HashMap<>();
        map.put("submemberApplyId", enterpriseSubmemberApply.getSubmemberApplyId());
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map), 1);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/updateSubmemberApplyStatus", method = RequestMethod.POST)
    public TResponse updateSubmemberApplyStatus(Long id, String status) {
        EnterpriseSubmemberApply apply = enterpriseSubmemberApplyService.selectByPrimaryKey(id);
        apply.setStatus(status);
        enterpriseSubmemberApplyService.updateByPrimaryKey(apply);
        return TResponse.SUCCESS();
    }


}
